package org.kolonitsky.translator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.kolonitsky.translator.Settings.ENCODING;

/**
 * @author Alex.Kolonitsky
 */

public class MicrosoftTranslator extends ServiceTranslator {

    protected static final Log LOG = LogFactory.getLog(Translator.class);

    private static final Pattern RESPONSE_XML = Pattern.compile("<string[^>]*>(.*)</\\s*string\\s*>");
    private static final String URL = "http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=" + Settings.MICROSOFT_APP_ID + "&text=%s&from=%s&to=%s";

    public MicrosoftTranslator(Lang to) {
    	this(to, DEFAULT_LIMIT);
    }

    public MicrosoftTranslator(Lang from, Lang to) {
        this(from, to, DEFAULT_LIMIT);
    }

    public MicrosoftTranslator(Lang to, int limit) {
        this(Lang.DEFAULT, to, limit);
    }

    public MicrosoftTranslator(Lang from, Lang to, int limit) {
        super(from, to, limit);
    }

    protected String translateChunk(String text) {
        String xmlStr = send(text);
        if (xmlStr == null) {
            return null;
        }

        Matcher matcher = RESPONSE_XML.matcher(xmlStr);
        if (!matcher.matches()) {
            return null;
        }

        return matcher.group(1);
    }

    protected URL getUrl(String text) throws MalformedURLException, UnsupportedEncodingException {
        return new URL(String.format(URL, URLEncoder.encode(text, ENCODING), from(), to()));
    }
}
